package com.ruge.system.service.impl;

import com.ruge.common.util.GsonUtil;
import com.ruge.system.pojo.entity.SysMenu;
import com.ruge.system.pojo.entity.SysRole;
import com.ruge.system.pojo.entity.SysRoleMenu;
import com.ruge.system.pojo.entity.SysUserRole;
import com.ruge.system.repository.SysRoleMenuRepository;
import com.ruge.system.repository.SysRoleRepository;
import com.ruge.system.repository.SysUserRoleRepository;
import com.ruge.system.pojo.request.RoleMenuRequest;
import com.ruge.system.pojo.request.RoleRequest;
import com.ruge.system.service.SysRoleService;
import com.ruge.system.pojo.vo.RoleVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 创建人 ：爱丽丝、如歌
 * 创建时间 ：2020-03-05  20:50
 * 描述 ：
 *
 * @author Administrator
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {
    @Resource
    private SysUserRoleRepository sysUserRoleRepository;
    @Resource
    private SysRoleRepository sysRoleRepository;
    @Resource
    private SysRoleMenuRepository sysRoleMenuRepository;

    /**
     * 通过用户id 查询 该用户的所有角色列表
     *
     * @param userId 用户id
     * @return 用户的角色
     */
    @Override
    public List<SysRole> findRolesByUserId(Long userId) {
        List<SysUserRole> roleIds = sysUserRoleRepository.findAllBySysUser_Id(userId);
        List<SysRole> list = new ArrayList<>();
        roleIds.forEach(e -> {
            sysRoleRepository.findById(e.getSysRole().getId()).ifPresent(list::add);
        });
        return list;
    }

    /**
     * 查询接口
     *
     * @param model
     * @return
     */
    @Override
    public Page<RoleVo> findAll(RoleRequest model) {
        Specification<SysRole> specification = (root, query, cb) -> {
            /**
             * 获取条件对象
             */
            Predicate conjunction = cb.conjunction();
            if (model != null) {
                if (null != model.getId()) {
                    conjunction.getExpressions().add(cb.equal(root.get("id"), model.getId()));
                }
                if (StringUtils.isNotBlank(model.getName())) {
                    conjunction.getExpressions().add(cb.like(root.get("name"), "%" + model.getName() + "%"));
                }
            }
            return conjunction;
        };
        Sort sort = Sort.by(Sort.Order.desc("sort"));
        Pageable pageable = PageRequest.of(model != null ? model.getPage() : 0, model != null ? model.getLimit() : 15, sort);
        Page<SysRole> page = sysRoleRepository.findAll(specification, pageable);
        return new PageImpl<>(GsonUtil.GsonToListVo(page.getContent(), RoleVo.class), pageable, page.getTotalElements());
    }

    /**
     * 不分页查询接口
     *
     * @param model
     * @return
     */
    @Override
    public List<RoleVo> findAllNoPage(RoleRequest model) {
        Specification<SysRole> specification = (root, query, cb) -> {
            /**
             * 获取条件对象
             */
            Predicate conjunction = cb.conjunction();
            if (model != null) {
                if (null != model.getId()) {
                    conjunction.getExpressions().add(cb.equal(root.get("id"), model.getId()));
                }
                if (StringUtils.isNotBlank(model.getName())) {
                    conjunction.getExpressions().add(cb.like(root.get("name"), "%" + model.getName() + "%"));
                }
            }
            return conjunction;
        };
        Sort sort = Sort.by(Sort.Order.desc("sort"));
        List<SysRole> list = sysRoleRepository.findAll(specification, sort);
        return  GsonUtil.GsonToListVo(list, RoleVo.class) ;
    }

    /**
     * 保存接口
     *
     * @param sysRole
     * @return
     */
    @Override
    public SysRole save(SysRole sysRole) {
        return sysRoleRepository.save(sysRole);
    }

    /**
     * 数据删除接口
     *
     * @param id
     * @return
     */
    @Override
    public void deleteById(Long id) {
        sysRoleRepository.deleteById(id);
        sysUserRoleRepository.deleteBySysRole_Id(id);
        sysRoleMenuRepository.deleteBySysRole_Id(id);
    }

    /**
     * 批量操作
     *
     * @param map
     * @return
     */
    @Override
    public List<SysRole> batch(Map<String, List<SysRole>> map) {
        return sysRoleRepository.batch(map);
    }

    /**
     * 给角色进行菜单授权
     *
     * @param list
     * @return
     */
    @Override
    public void authMenu(List<RoleMenuRequest> list) {
        list.forEach(e->{
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            SysRole sysRole = new SysRole();
            sysRole.setId(e.getRid());
            SysMenu sysMenu = new SysMenu();
            sysMenu.setId(e.getMid());
            sysRoleMenu.setSysRole(sysRole);
            sysRoleMenu.setSysMenu(sysMenu);
            sysRoleMenuRepository.save(sysRoleMenu);
        });
    }

    /**
     * 获取角色授权id 进行数据返现
     *
     * @param roleId
     * @return
     */
    @Override
    public List<Long> getAuthMenu(Long roleId) {
        return  sysRoleMenuRepository.findAllBySysRole_Id(roleId).stream().map(SysRoleMenu::getSysMenu).map(SysMenu::getId).collect(Collectors.toList());
    }
}
